package com.boful.convert.core;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ConvertProviderConfig {
	private String name;
	private String description;
	private List<HostConfig> hosts = new ArrayList<HostConfig>();
	private static final Logger LOGGER = Logger.getLogger(ConvertProviderConfig.class);
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public List<HostConfig> getHosts() {
		return hosts;
	}

	public void setHosts(List<HostConfig> hosts) {
		this.hosts = hosts;
	}

	@SuppressWarnings("unchecked")
	public void init(Element rootElement) {
		Element providerRootElement = rootElement.element("providers");
		List<Element> providerList = providerRootElement.elements("provider");
		for (Element element : providerList) {
			LOGGER.debug("正在解析节点："+element.getPath());
			Element providerNameElement = element.element("name");
			Element providerDescElement = element.element("description");
			Element hostsElement = element.element("hosts");
			List<Element> hostList = hostsElement.elements("host");

			setName(providerNameElement.getText());
			setDescription(providerDescElement.getText());
			LOGGER.debug("hosts size："+hostList.size());
			for (Element hostNode : hostList) {
				LOGGER.debug(hostNode.getPath());
				HostConfig hostConfig = new HostConfig();
				hostConfig.init(hostNode);
				getHosts().add(hostConfig);
			}

		}
	}

	public void init(File convertXml) throws IOException, DocumentException {
		SAXReader SR = new SAXReader();
		Document doc = SR.read(convertXml);
		Element rootElement = doc.getRootElement();
		init(rootElement);

	}

}
